package com.modular.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.RegisteredPayload;
import com.modular.common.Principal;
import com.modular.common.UserGrantedAuthority;
import com.modular.vo.security.BaseLogin;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.*;
import java.util.stream.Collectors;

public class SecurityUtil {

    private static final Principal EMPTY = new Principal();

    public SecurityUtil() {
    }

    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获得缓存中的用户信息
     * @return
     */
    public static Authentication getPrincipal() {
        return getAuthentication();
    }

    /**
     * 将数据保存在
     * @param principal
     */
    public static void setSecurityContextAuthentication(BaseLogin principal) {
        if (ObjectUtil.isNotNull(principal)) {
            List<String> authorities = principal.getAuthorities();
            Set<? extends GrantedAuthority> authorityList = createAuthorityList(authorities);
            Authentication authentication = new UsernamePasswordAuthenticationToken(principal, (Object)null, authorityList);
            SecurityContext securityContext = SecurityContextHolder.getContext();
            securityContext.setAuthentication(authentication);
        }
    }

    private static Set<? extends GrantedAuthority> createAuthorityList(List<String> authorities) {
        return !CollUtil.isEmpty(authorities) ? authorities.stream().filter(StrUtil::isNotBlank).map(UserGrantedAuthority::getInstance).collect(Collectors.toSet()) : Collections.emptySet();
    }

}
